package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"openzbox.com/driver/conn/serial"
	"openzbox.com/log"
	"openzbox.com/utils/crc"
	"os"
	"strings"
	"time"
)

func main() {

	var portPath = "/dev/ttyS1"
	var DataBit int = 8
	var StopBit int = 1
	var portBaud int = 9600
	//var pwreset bool = false
	//flag.IntVar(&portNumber, "p", 1, "portnumber index [1-6].")
	flag.StringVar(&portPath, "f", "/dev/ttyS1", "/dev/ttyS[num]")
	flag.IntVar(&DataBit, "db", 8, "databits default 8.")
	flag.IntVar(&StopBit, "sb", 1, "stopbits default 1.")

	flag.IntVar(&portBaud, "b", 9600, "portbaud default 9600.")
	//flag.BoolVar(&pwreset, "r",false,  "reboot power.")
	flag.Parse()
	log.Infof("Welcome, OpenZbox Uart Tools...")

	if len(os.Args) <= 1 {
		//flag.PrintDefaults()
		flag.PrintDefaults()
		os.Exit(0)
	}
	//potNumberIdx := []int{ 0,8,3,7,6,4,5}

	log.Infof("Open %s@%d ...", portPath, portBaud)
	/*
		options := serial.OpenOptions{
			PortName:        portPath,
			BaudRate:        physic.Frequency(portBaud),
			DataBits:        DataBit,
			StopBits:        StopBit,
			MinimumReadSize: 1,
		}*/
	options := serial.Config{
		Address:  portPath,
		BaudRate: portBaud, //physic.Frequency(portBaud),
		DataBits: DataBit,
		StopBits: StopBit,
		//MinimumReadSize: 1,
	}
	// Open the port.
	port, err := serial.Open(&options)
	if err != nil {
		log.Fatalf("serial.Open: %v", err)
	}

	// Make sure to close it later.
	defer port.Close()
	str := ""
	dataline := make([]byte, 128)

	ticker := time.NewTicker(time.Millisecond * 1000)
	//i:=0
	if 1 == 2 {
		go func() {
			l := 1100
			r := 1900
			relay := 0
			for { //循环
				<-ticker.C
				l = l + 10
				if l >= 1900 {
					l = 1100
				}
				r = r - 10
				if r <= 1100 {
					r = 1900
				}
				if l%100 == 0 {
					relay = 1
				} else {
					relay = 0
				}
				//log.Info(".....")
				sendcmd := fmt.Sprintf("#DBMLR,%d,%d,%d,", l, r, relay)
				crc := crc.CalculateCRC(crc.CRC16MODBUS, []byte(sendcmd))
				sx := fmt.Sprintf("%s*%04x\r\n", sendcmd, crc)
				b := []byte(sx)
				//if(i<=100) {
				_, terr := port.Write(b)
				if terr != nil {
					log.Errorf("port.Write: %v", err)
				}
				//	i++
				///}

			}
		}()
	}
	if 1 == 2 {
		go func() {
			//v:=1
			for { //循环
				<-ticker.C
				//if(v==1) {
				sendcmd := fmt.Sprintf("OL000255000003")
				b := []byte(sendcmd)
				//if(i<=100) {
				_, terr := port.Write(b)
				if terr != nil {
					log.Errorf("port.Write: %v", err)
				}
				log.Infof("%s", sendcmd)
				//v=0;
				//continue;
				/*}else {
					sendcmd := fmt.Sprintf("AA000000000")
					b := []byte(sendcmd)
					//if(i<=100) {
					_, terr := port.Write(b)
					if terr != nil {
						log.Errorf("port.Write: %v", err)
					}
					log.Infof("%s", sendcmd)
					v=1;
					continue;
				}*/
			}
		}()
	}
	for {

		/**/
		// Write 4 bytes to the port.
		//fmt.Println("Wrote", n, "bytes.")
		//port.Write(nil)
		buf := make([]byte, 1)
		rx, rerr := port.Read(buf)
		if rerr != nil {
			if rerr != io.EOF {
				log.Errorf("Error reading from serial port: ", rerr)
			}
		} else {
			buf = buf[:rx]
			//	fmt.Println("Rx: ", string(buf))
			//devid = string(bytes.Trim(buf, "\x00"))
			dataline = append(dataline, buf...)
			//log.Infof(string(dataline))
			if strings.HasSuffix(string(dataline), "\n") {
				//lg函数本身已有换行，因此清除掉返回数据中的回车换行符
				str = string(bytes.Trim(dataline, "\x00")) //[0:24]
				str = strings.ReplaceAll(str, "\r\n", "")
				log.Infof(str)
				//清空数组以重新接受rs485数据
				dataline = make([]byte, 128)
				//break
			}
		}
		//time.Sleep(time.Second * (time.Duration(1)))
	}

}
